﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Home.Framework.Infrastructure
{
    public class Messenger
    {
        public Messenger()
        {
            this.MessageTimer = new ServiceTimer();
            this.MessageStack = new Stack<ServiceMessage>();
        }

        public ServiceTimer MessageTimer { get; set; }

        public Stack<ServiceMessage> MessageStack { get; set; }

        public ServiceMessage ServiceMsg 
        { 
            get
            {
                return this.MessageStack.Peek();
            }
        }

        public string Remark { get; set; }        

        public ResponseState ReturnState
        {
            get
            {
                return this.ServiceMsg.ServiceState;
            }
        }

        public int State
        {
            get
            {
                return EnumUtils.GetValue(this.ReturnState);
            }
        }

        public string StateName
        {
            get
            {
                return EnumUtils.GetName(this.ReturnState);
            }
        }

        public TimeSpan Interval
        {
            get
            {
                return this.MessageTimer.Interval;
            }
        }

        public void ReceiveException(Exception exception)
        {
            ServiceMessage msg = new ServiceMessage();
            msg.MessageException = exception;
            msg.ServiceState = ResponseState.异常;
            this.PushMessage(msg);
        }

        public void ReceiveMessage(Enum msgType)
        {
            ServiceMessage msg = new ServiceMessage();
            msg.MessageType = msgType;
            msg.ServiceState = ResponseState.成功;
            this.PushMessage(msg);
        }

        public void ReceiveError(Enum errorType)
        {
            ServiceMessage msg = new ServiceMessage();
            msg.MessageType = errorType;
            msg.ServiceState = ResponseState.失败;
            this.PushMessage(msg);
        }

        protected void PushMessage(ServiceMessage serviceMsg)
        {
            this.MessageStack.Push(serviceMsg);
            this.MessageTimer.UpdateTimer(serviceMsg.UpdateTime);
        }
    }
}